package com.lewis.system.manager.factory;

import com.lewis.core.constant.Constants;
import com.lewis.core.utils.ServletUtil;
import com.lewis.core.utils.SpringUtil;
import com.lewis.core.utils.StringUtil;
import com.lewis.core.utils.ip.AddressUtil;
import com.lewis.core.utils.ip.IpUtil;
import com.lewis.system.entity.SysLogLogin;
import com.lewis.system.entity.SysLogOperational;
import com.lewis.system.service.ISysLogLoginService;
import com.lewis.system.service.ISysLogOperationalService;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author Lewis
 */
@Slf4j
public class AsyncFactory {

	/**
	 * 记录登录信息
	 *
	 * @param username 用户名
	 * @param status   状态
	 * @param message  消息
	 * @param args     列表
	 * @return 任务task
	 */
	public static TimerTask recordLoginInFor(final String username, final String status, final String message, final Object... args) {
		final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtil.getRequest().getHeader("User-Agent"));
		final String ip = IpUtil.getIpAddr(ServletUtil.getRequest());
		return new TimerTask() {
			@Override
			public void run() {
				String address = AddressUtil.getRealAddressByIp(ip);
				String sb = getBlock(ip) +
						address +
						getBlock(username) +
						getBlock(status) +
						getBlock(message);
				// 打印信息到日志
				log.info(sb, args);
				// 获取客户端操作系统
				String os = userAgent.getOperatingSystem().getName();
				// 获取客户端浏览器
				String browser = userAgent.getBrowser().getName();
				// 封装对象
				SysLogLogin sysLogLogin = new SysLogLogin();
				sysLogLogin.setUserName(username);
				sysLogLogin.setIpaddr(ip);
				sysLogLogin.setLoginLocation(address);
				sysLogLogin.setBrowser(browser);
				sysLogLogin.setOs(os);
				sysLogLogin.setMsg(message);
				// 日志状态
				if (StringUtil.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)){
					sysLogLogin.setStatus(Constants.SUCCESS);
				} else if (Constants.LOGIN_FAIL.equals(status)) {
					sysLogLogin.setStatus(Constants.FAIL);
				}
				// 插入数据
				SpringUtil.getBean(ISysLogLoginService.class).save(sysLogLogin);
			}
		};
	}

	/**
	 * 操作日志记录
	 *
	 * @param operLog 操作日志信息
	 * @return 任务task
	 */
	public static TimerTask recordOper(final SysLogOperational operLog) {
		return new TimerTask() {
			@Override
			public void run() {
				// 远程查询操作地点
				operLog.setOperLocation(AddressUtil.getRealAddressByIp(operLog.getOperIp()));
				SpringUtil.getBean(ISysLogOperationalService.class).save(operLog);
			}
		};
	}

	public static String getBlock(Object msg) {
		if (msg == null) {
			msg = "";
		}
		return "[" + msg.toString() + "]";
	}
}
